<script setup>
import { ref } from "vue";
import {notification} from 'ant-design-vue';
const totalValue = ref(0)
const rawText = ref("")
const setValue = ref(5000)
const splitValue = ref(2500)
const Rate1 = ref(0.97)
const Rate2 = ref(47.5)
const Rate3 = ref(0.7)
const round = ref(1)
const col0 = ref("")
const col1 = ref("")
const col2 = ref("")
const col3 = ref("")
const col4 = ref("")
const col5 = ref("")
const col6 = ref("")
const col7 = ref("")
const col8 = ref("")
const result = ref("")
const result2 = ref("")
const result3 = ref("")

function handleProcessData(text) {
  text = text.replace(/\s+/g, ' ')
  text = text.replace(/\s*=\s*/g, '=');
  const splitList = text.split(' ')
  const col0List = []
  const col1List = []
  const col2List = []
  const col3List = []
  const col4List = []
  const col5List = []
  const col6List = []
  const col7List = []
  const col8List = []
  const resultList = []
  const result2List = []
  const result3List = []
  const allList = []
  let order = 1
  let sum = 0
  splitList.forEach(ele => {
    col0List.push(order)
    order++
    let [a,b=''] = ele.split('=')
    const base = Math.pow(10, round.value)
    let minus = setValue.value-b
    if (minus < 0) {
      minus = 0
    }
    let roundMinus = Math.round(minus/base)*base
    roundMinus = parseInt((roundMinus * Rate3.value).toFixed(0))
    sum += parseInt(roundMinus)
    let split1 = 0
    let split2 = 0
    if (roundMinus >= splitValue.value) {
      split1 = splitValue.value
      split2 = roundMinus - splitValue.value
    } else {
      split2 = roundMinus
    }
    const m = {
      num: a, // 序号
      rawValue: b, // 原始数值
      minus, // 设定值 - 原始数值
      roundMinus, // 四舍五入后的（设定值-原始数值）
      split1, // 拆分值（小的时候，则为0）
      split2,  // 总值-拆分值,
      rateValue: 0
    }
    allList.push(m)
  })
  totalValue.value = sum
  allList.forEach(ele => {
    // ele.rateValue = (sum * Rate1.value - Math.round(ele.rawValue * Rate2.value) * Rate3.value).toFixed(0)
    ele.rateValue = (ele.roundMinus * Rate2.value - sum * Rate1.value).toFixed(0)
  })
  allList.sort((a,b) => {
    return a.rawValue - b.rawValue
  })
  allList.forEach(ele => {{
    resultList.push(`${ele.num}=${ele.roundMinus}`)
    if (ele.split1 > 0) {
      result2List.push(`${ele.num}=${ele.split1}`)
    }
    if (ele.split2 > 0) {
      result3List.push(`${ele.num}=${ele.split2}`)
    }
    col8List.push(ele.rateValue)
    col1List.push(`${ele.num}=${ele.rawValue}`)
    col2List.push(ele.num)
    col3List.push(ele.rawValue)
    col4List.push(ele.minus)
    col5List.push(ele.roundMinus)
    col6List.push(ele.split1)
    col7List.push(ele.split2)
  }})
  col0.value = col0List.join('\r\n')
  col1.value = col1List.join('\r\n')
  col2.value = col2List.join('\r\n')
  col3.value = col3List.join('\r\n')
  col4.value = col4List.join('\r\n')
  col5.value = col5List.join('\r\n')
  col6.value = col6List.join('\r\n')
  col7.value = col7List.join('\r\n')
  col8.value = col8List.join('\r\n')
  result.value = resultList.join(' ')
  result2.value = result2List.join(' ')
  result3.value = result3List.join(' ')
}

async function handleCopy(text) {
  console.log('handleCopy', text)
  try {
    if (window.isSecureContext && navigator.clipboard) {
      await navigator.clipboard.writeText(text);
      let prompt = text.substring(0, 50)
      if (text.length > 50) {
        prompt += '...'
      }
      notification.open({
        message: '复制成功',
        description: `复制内容：【${prompt}】`
      })
    } else {
      unsecuredCopyToClipboard(text);
    }
  } catch (error) {
    console.log(error)
  }
  async function unsecuredCopyToClipboard(text) {
        const textArea = document.createElement("textarea");
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        try {
            document.execCommand('copy');
            let prompt = text.substring(0, 50)
            if (text.length > 50) {
            prompt += '...'
            }
            notification.open({
              message: '复制成功',
              description: `复制内容：【${prompt}】`
            })
        } catch (err) {
            console.error('Unable to copy to clipboard', err);
        }
        document.body.removeChild(textArea);
    }
}
</script>
<template>
  <div class="wrapper">
    <h3>原始数据</h3>
    <a-textarea
      v-model:value="rawText"
      placeholder="输入需要切割的数据"
      :auto-size="{ minRows: 2 }"
      @change="handleProcessData(rawText)"
    />


    设定值：<a-input style="width: 128px;" v-model:value="setValue" @change="handleProcessData(rawText)"></a-input>
    拆分值：<a-input style="width: 128px;" v-model:value="splitValue" @change="handleProcessData(rawText)"></a-input>
    比例：<a-input style="width: 128px;" v-model:value="Rate3" @change="handleProcessData(rawText)"></a-input>
    Rate1：<a-input style="width: 128px;" v-model:value="Rate1" @change="handleProcessData(rawText)"></a-input>
    Rate2：<a-input style="width: 128px;" v-model:value="Rate2" @change="handleProcessData(rawText)"></a-input>
    <br>
    四舍五入：
    <a-radio-group v-model:value="round" button-style="solid" @change="handleProcessData(rawText)">
      <a-radio-button :value="0">个</a-radio-button>
      <a-radio-button :value="1">整十</a-radio-button>
      <a-radio-button :value="2">整百</a-radio-button>
      <a-radio-button :value="3">整千</a-radio-button>
      <a-radio-button :value="4">整万</a-radio-button>
    </a-radio-group>
    <a-button style="margin: 1em;" type="primary" @click="handleProcessData(rawText)">处理数据</a-button>
    总和：{{ totalValue }}
    <h3>处理结果(四舍五入)</h3>
    <a-textarea
      v-model:value="result"
      :auto-size="{ minRows: 2 }"
    />
    <a-button type="primary" @click="handleCopy(result)">复制</a-button>
    <a-divider></a-divider>

    <h3>处理结果(拆分-固定)</h3>
    <a-textarea
      v-model:value="result2"
      :auto-size="{ minRows: 2 }"
    />
    <a-button type="primary" @click="handleCopy(result2)">复制</a-button>
    <a-divider></a-divider>

    <h3>处理结果(拆分-余数)</h3>
    <a-textarea
      v-model:value="result3"
      :auto-size="{ minRows: 2 }"
    />
    <a-button type="primary" @click="handleCopy(result3)">复制</a-button>
    <a-divider></a-divider>
    <h3>切割结果</h3>
    <div style="display: flex;">
      <!-- TODO:增加序号 -->
      <!-- <div class="result-item">
        <div
          style="width: 32px;margin-top: 32px;"
        >{{ col0 }}</div>
      </div> -->
      <div class="result-item">
        <a-button type="primary" @click="handleCopy(col1)">复制</a-button>
        <a-textarea
          v-model:value="col1"
          :auto-size="{ minRows: 2 }"
        />
      </div>
      <div class="result-item">
        <a-button type="primary" @click="handleCopy(col2)">复制</a-button>
        <a-textarea
          v-model:value="col2"
          :auto-size="{ minRows: 2 }"
        />
      </div>
      <div class="result-item">
        <a-button type="primary" @click="handleCopy(col3)">复制</a-button>
        <a-textarea
          v-model:value="col3"
          :auto-size="{ minRows: 2 }"
        />
      </div>
      <!-- <div class="result-item">
        <a-button type="primary" @click="handleCopy(col4)">复制</a-button>
        <a-textarea
          v-model:value="col4"
          :auto-size="{ minRows: 2 }"
        />
      </div> -->
      <div class="result-item">
        <a-button type="primary" @click="handleCopy(col4)">复制</a-button>
        <a-textarea
          v-model:value="col8"
          :auto-size="{ minRows: 2 }"
        />
      </div>
      <div class="result-item">
        <a-button type="primary" @click="handleCopy(col5)">复制</a-button>
        <a-textarea
          v-model:value="col5"
          :auto-size="{ minRows: 2 }"
        />
      </div>
      <div class="result-item">
        <a-button type="primary" @click="handleCopy(col6)">复制</a-button>
        <a-textarea
          v-model:value="col6"
          :auto-size="{ minRows: 2 }"
        />
      </div>
      <div class="result-item">
        <a-button type="primary" @click="handleCopy(col7)">复制</a-button>
        <a-textarea
          v-model:value="col7"
          :auto-size="{ minRows: 2 }"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.wrapper {
  max-width: 1080px;
  margin: 64px auto;
}
.result-item {
  margin-left: 1em;
}
.result-item:first-child {
  margin-left: 0;
}
</style>
